package com.example.springbootminiodemo.common.beans;

import com.example.springbootminiodemo.config.MinioConfig;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * 表示共同的mini io 服务
 *
 * @auther: lihh
 */
@Component
public class MinioBean {
  @Autowired
  private MinioClient minioClient;
  @Autowired
  private MinioConfig minioConfig;
  
  
  /**
   * 创建桶 如果桶已经存在的话 直接跳过
   *
   * @param bucketName 表示桶的名称
   * @throws Exception
   */
  public void createBucket(String bucketName) throws Exception {
    if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build()))
      minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
  }
  
  
  /**
   * 表示上传文件的逻辑
   *
   * @param bucketName  表示桶名称
   * @param file        以及上传的文件
   * @param newFileName 表示新的文件名称
   * @return
   * @throws Exception
   */
  
  public String uploadFile(String bucketName, MultipartFile file, String newFileName) throws Exception {
    if (newFileName == null || newFileName == "") {
      newFileName = UUID.randomUUID().toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    }
    minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(newFileName).stream(file.getInputStream(), file.getInputStream().available(), -1).contentType(file.getContentType()).build());
    return minioConfig.getEndpoint() + "/" + bucketName + "/" + newFileName;
  }
  
  public String uploadFile(String bucketName, MultipartFile file) throws Exception {
    return uploadFile(bucketName, file, null);
  }
  
  public InputStream downloadFile(String bucketName, String filename) throws Exception {
    return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(filename).build());
  }
}
